package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = this.baseMapper.selectList(null);
        List<CategoryEntity> categoryEntityList = entities.stream().filter(item -> item.getParentCid() == 0).map(
                (categoryEntity) -> {
              categoryEntity.setChildren(getChildren(categoryEntity,entities));
              return categoryEntity;
                }
                ).sorted((c1, c2) -> ((c1.getSort()==null?0:c1.getSort()) - (c2.getSort()==null?0: c2.getSort()))).collect(Collectors.toList());

        return categoryEntityList;
    }

    private List<CategoryEntity> getChildren(CategoryEntity categoryEntity, List<CategoryEntity> entities) {
        List<CategoryEntity> list = entities.stream().filter(item -> item.getParentCid() == categoryEntity.getCatId())
                .map(c -> {
                    c.setChildren(getChildren(c,entities));
                    return c;
                })
                .sorted((c1, c2) -> ((c1.getSort()==null?0:c1.getSort()) - (c2.getSort()==null?0: c2.getSort()))).collect(Collectors.toList());
        return list;
    }

}